<?php

class Helper extends CController {

    public static function truncate_utf8_string($string, $length, $etc = '...') {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++) {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0')) {
                if ($length < 1.0) {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            } else {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen) {
            $result .= $etc;
        }
        return $result;
    }

    public static function datetime_to_date($date) {
        return date('Y-m-d', strtotime($date));
    }

    //統計用戶的返點和購物金是否到期
    public static function accounting($uid) {
        $user = User::model()->findByPk((int) $uid);
        if ($user) {
            if ($user->hy_expiry && strtotime($user->hy_expiry) < time()) {
                //添加鴻運點數清空記錄并且清空鴻運點數
                $trans = Yii::app()->db->beginTransaction();
                try {
                    //流水記錄保存
                    $record = new CoinFlow();
                    $record->uid = $uid;
                    $record->type = 2;
                    $record->amount = $user->hongyun;
                    $record->flow_type = 2;
                    $record->description = '鴻運點數到期自動清空';
                    $record->save();

                    //用戶記錄保存
                    $user->hy_expiry = '';
                    $user->hongyun = 0;
                    //保存訂單的返點和返金幣
                    $user->save();
                    //提交
                    $trans->commit();
                } catch (Exception $e) {
                    $trans->rollback();
//                    echo $e->getMessage();
//            $this->response(array('status' => 1, 'msg' => $e->getMessage()));
                }
            }
            if ($user->coin_expiry && strtotime($user->coin_expiry) < time()) {
                //添加鴻運點數清空記錄并且清空鴻運點數
                $trans = Yii::app()->db->beginTransaction();
                try {
                    //流水記錄保存
                    $record = new CoinFlow();
                    $record->uid = $uid;
                    $record->type = 1;
                    $record->amount = $user->coin;
                    $record->flow_type = 2;
                    $record->description = '金幣到期自動清空';
                    $record->save();

                    //用戶記錄保存
                    $user->coin_expiry = '';
                    $user->coin = 0;
                    //保存訂單的返點和返金幣
                    $user->save();
                    //提交
                    $trans->commit();
                } catch (Exception $e) {
                    $trans->rollback();
//                    echo $e->getMessage();
//            $this->response(array('status' => 1, 'msg' => $e->getMessage()));
                }
            }
        }
    }

    //根據訂單增加點數和購物金記錄
    public static function addCoinByOrder($oid) {
        $order = Order::model()->findByPk((int) $oid);
        if ($order) {
            //鴻運點數
            if ($order->hongyun_return > 0) {
                $item = new CoinItem();
                $item->uid = $order->uid;
                $item->oid = $order->oid;
                $item->amount = $order->hongyun_return;
                $item->type = 2;
                $item->source = 1;
                $item->status = 1;
                $item->effectdate = date('Y-m-d', strtotime('+30 day'));
                $item->save();
                unset($item);
            }

            //購物金
            if ($order->coin_return > 0) {
                $item = new CoinItem();
                $item->uid = $order->uid;
                $item->oid = $order->oid;
                $item->amount = $order->coin_return;
                $item->type = 1;
                $item->source = 1;
                $item->status = 1;
                $item->effectdate = date('Y-m-d', strtotime('+30 day'));
                $item->save();
                unset($item);
            }
        }
    }

    //根據訂單取消點數和購物金記錄
    public static function cancelCoinByOrder($oid) {
        $order = Order::model()->findByPk((int) $oid);
        if ($order) {
            $criteria = new CDbCriteria();
            $criteria->addCondition('oid=' . $order->oid);
            $criteria->addCondition('status=1');
            $result = CoinItem::model()->updateAll(array('status' => 3), $criteria);
            unset($criteria);
        }
    }

    //驗證用戶是否通過驗證的客戶
    public static function userStatus($uid) {
        $user = User::model()->findByPk($uid);
        $status = true;
        if ($user) {
            if (Yii::app()->params['emailVerify'] && $user->email_status == 0) {
                $status = false;
            }
            if (Yii::app()->params['mobileVerify'] && $user->mobile_status == 0) {
                $status = false;
            }
        } else {
            $status = false;
        }
        return $status;
    }

    //即將生效的鴻運點數和購物金
    public static function getunEffectCoin($type, $uid) {
        $connection = Yii::app()->db;
        $sql = "select sum(amount) as amount
from iteam_coin_item
where uid=$uid
and type=$type
and status=1
";
        $command = $connection->createCommand($sql);
        $result = $command->queryRow();
        return $result['amount'];
    }

    //購物金及鴻運點數生效
    public static function coinComeTrue($uid = 0) {
        $condition = new CDbCriteria();
        $condition->addCondition('status=1');
        $condition->addCondition("effectdate<='" . date("Y-m-d") . "'");
        if ($uid) {
            $condition->addCondition('uid=' . $uid);
        }
        $rowset = CoinItem::model()->findAll($condition);
        unset($condition);
        if ($rowset) {
            foreach ($rowset as $row) {
                Helper::accounting($row->uid);
                $trans = Yii::app()->db->beginTransaction();
                try {
                    //更新用戶記錄中的餘額及失效日期
                    $user = User::model()->findByPk($row->uid);

                    if ($user) {
                        $row->status = 2; //已生效
                        if ($row->type == 1) {
                            $user->coin += $row->amount;
                            $user->coin_expiry = date('Y-m-d', strtotime('+1 year'));
                        } elseif ($row->type == 2) {
                            $user->hongyun += $row->amount;
                            $user->hy_expiry = date('Y-m-d', strtotime('+1 year'));
                        }
                        $user->save();
                    } else {
                        $row->status = 4; //用戶不存在給個特殊狀態，下次不處理了
                    }

                    //更新記錄狀態
                    $row->save();

                    //流水記錄保存
                    $record = new CoinFlow();
                    $record->uid = $user->uid;
                    $record->type = $row->type;
                    $record->amount = $row->amount;
                    $record->flow_type = 1;
                    $record->description = 'coin item表記錄生效(' . $row->iid . ')';
                    $record->save();

                    //提交
                    $trans->commit();
                } catch (Exception $e) {
                    $trans->rollback();
//                    echo $e->getMessage();
                }
            }
        }
    }

    //上傳圖片
    public static function uploadPic($model, $path, $field = 'pic') {
        $file = CUploadedFile::getInstance($model, $field); //获取表单名为filename的上传信息
//            $filename=$file->getName();//获取文件名
        if ($file) {
            $filesize = $file->getSize(); //获取文件大小
            $filetype = $file->getType(); //获取文件类型
            $hg = explode('.', $file->getName());
            $hgc = count($hg) - 1;
            $hg = $hg[$hgc];
            $filename = time() . rand(100, 999) . '.' . $hg;

            $uploadfile = $path . '/' . $filename;
            if ($file->saveAs($uploadfile, true)) {
                return $filename;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //活動自動開始
    public static function openActivity($aid = 0) {
        $condition = new CDbCriteria();
        $condition->addCondition('status=1');
        $condition->addCondition("starttime<='" . date('Y-m-d H:i:s') . "'");
        if ($aid) {
            $condition->addCondition('activityid=' . $aid);
        }
        $rowset = Activity::model()->findAll($condition);
        if ($rowset) {
            foreach ($rowset as $row) {
                $row->status = 2;
                $row->save();
            }
        }
    }

    //活動關閉
    public static function closeActivity($aid = 0) {
        $condition = new CDbCriteria();
        $condition->addCondition('status=2');
        if ($aid) {
            $condition->addCondition('activityid=' . $aid);
        }
        $rowset = Activity::model()->findAll($condition);
        if ($rowset) {
            foreach ($rowset as $row) {
                $row->status = 3;
                $row->endtime = date('Y-m-d H:i:s');
                $row->save();
            }
        }
    }

    //開獎
    public static function winPrize($aid = 0) {
        $condition = new CDbCriteria();
        $condition->addCondition('status=3');
        $condition->addCondition("class='時間限定'");
        if ($aid) {
            $condition->addCondition('activityid=' . $aid);
        }
        $rowset = Activity::model()->findAll($condition);
        unset($condition);
        if ($rowset) {
            foreach ($rowset as $row) {
                $trans = Yii::app()->db->beginTransaction();
                try {
                    //活動記錄保存，更新為待開獎
                    $row->endtime = date('Y-m-d H:i:s');
                    $row->status = 5;
                    $row->save();

                    //取隨機用戶作為中獎用戶
                    $connection = Yii::app()->db;
                    $sql = "SELECT t1.rid
FROM `iteam_record` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(rid) FROM `iteam_record`)-(SELECT MIN(rid) FROM `iteam_record`))+(SELECT MIN(rid) FROM `iteam_record`)) AS rid) AS t2 
WHERE t1.rid >= t2.rid and t1.activityid=" . $row->activityid . "
ORDER BY t1.rid LIMIT " . $row->winner . "; ";
                    $command = $connection->createCommand($sql);
                    $wins = $command->queryAll();

                    $ridArr = array();
                    if ($wins) {
                        foreach ($wins as $win) {
                            $ridArr[] = $win['rid'];
                        }
                    }

//                    var_dump($ridArr);

                    $condition = new CDbCriteria();
                    $condition->addInCondition('rid', $ridArr);
                    Record::model()->updateAll(array('win' => 1), $condition);
                    unset($condition);

                    //提交
                    $trans->commit();
                } catch (Exception $e) {
                    $trans->rollback();
                }
            }
        }
    }

    //檢查身份證
    public static function check_identity($id) {
        $flag = false;
        $id = strtoupper($id);
        $d0 = strlen($id);
        $qd = "";
        if ($d0 <= 0) {
            $qd = $qd . "還沒填呢 !n";
        }
        if ($d0 > 10) {
            $qd = $qd . "超過10個字 !n";
        }
        if ($d0 < 10 && $d0 > 0) {
            $qd = $qd . "不滿10個字 !n";
        }
        $d1 = substr($id, 0, 1);
        $ds = ord($d1);
        if ($ds > 90 || $ds < 65) {
            $qd = $qd . "第一碼必須是大寫的英文字母 !n";
        }
        $d2 = substr($id, 1, 1);
        if ($d2 != "1" && $d2 != "2") {
            $qd = $qd . "第二碼有問題 !n";
        }
        for ($i = 1; $i < 10; $i++) {
            $d3 = substr($id, $i, 1);
            $ds = ord($d3);
            if ($ds > 57 || $ds < 48) {
                $n = $i + 1;
                $qd = $qd . "第二到十碼有問題 !n";
                break;
            }
        }
        $num = array("A" => "10", "B" => "11", "C" => "12", "D" => "13", "E" => "14",
            "F" => "15", "G" => "16", "H" => "17", "J" => "18", "K" => "19", "L" => "20",
            "M" => "21", "N" => "22", "P" => "23", "Q" => "24", "R" => "25", "S" => "26",
            "T" => "27", "U" => "28", "V" => "29", "X" => "30", "Y" => "31", "W" => "32",
            "Z" => "33", "I" => "34", "O" => "35");
        $n1 = substr($num[$d1], 0, 1) + (substr($num[$d1], 1, 1) * 9);
        $n2 = 0;
        for ($j = 1; $j < 9; $j++) {
            $d4 = substr($id, $j, 1);
            $n2 = $n2 + $d4 * (9 - $j);
        }
        $n3 = $n1 + $n2 + substr($id, 9, 1);
        if (($n3 % 10) != 0) {
            $qd = $qd . "不通過 !n";
        }
        if ($qd == "") {
            $flag = true;
        }
        return $flag;
    }

    //驗證郵箱
    public static function check_email($email) {
        if (preg_match("/^[0-9a-zA-Z]+(?:[\_\-\.][a-z0-9\-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+$/i", $email)) {
            return true;
        } else {
            return false;
        }
    }

    //獲取用戶下次參與活動的時間
    public static function getNextTime($uid) {
        $row = Config::model()->findByPk(1);
        $condition = new CDbCriteria();
        $condition->addCondition('uid=' . $uid);
        $condition->order = 'dateline desc';
        $last = Record::model()->find($condition);
        unset($condition);
        $time = strtotime($last->dateline) + $row->interval - time();
        if ($time < 0) {
            $time = 0;
        }
        return $time;
    }

    //取消訂單通知函
    public static function cancelOrderEmail($oid) {
        $order = Order::model()->findByPk($oid);
        if ($order) {
            $title = '您的 Jowin!揪贏網 訂購單(' . $oid . ')取消處理結果通知函';
            $content = '親愛的 ' . $order->user->realname . ' 您好:<br /><br />
您的訂購單(' . $oid . ')已取消完成。<br />
您此次的取消的訂購單明細如下，若您對於此筆訂購單的取消有任何疑問，請您依據訂購單單號與「客服中心」聯繫，我們會盡速協助處理，謝謝您!<br />
訂單編號：' . $order->oid . '<br />
訂購時間：' . date('Y/m/d H:i:s', strtotime($order->dateline)) . '<br />
付款方式：' . Yii::app()->params['paytype'][$order->pay_type] . '<br />
';
            foreach ($order->items as $item) {
                $content.= '商品名稱 : ' . $item->product->pname . ' * ' . $item->number . '<br />
';
            }
            $content.='<br />
To Jowin Member,<br />
This is a message from Jowin.com in Chinese Big5 code.<br />
We have received your online inquiry. If the Chinese text cannot be displayed properly, please go to https://myaccount.jowinwin.com to check your order status.<br /><br />

Thank You.<br /><br />

※貼心提醒 : <br />
1.	1.	基於個人資料安全維護原則，我們不會於往來信件中顯示完整訂購/出貨明細，若您想要進一步查詢訂單明細，請至 Jowin!揪贏網 「會員專區」中之「查詢訂單」選項中查詢。<br /><br />

Jowin!揪贏網團隊 敬上<br /><br />

____________________________________________________________________________________________<br />
Jowin!揪贏網 <br />
http://www.jowinwin.com

Jowin!揪贏網 Facebook粉絲團連結<br />
https://www.facebook.com/pages/Join-To-Win-%E6%8F%AA%E8%B4%8F%E7%B6%B2/137786092972951<br /><br />

客服中心連結 : www.jowinwin.com/service
';
            $result = Helper::sentEmailSmtp($order->user->email, $title, $content);
//            var_dump($result);exit;
        }
    }

    //發送郵件類SMTP
    public static function sentEmailSmtp($to, $title, $content, $att = '') {
        set_time_limit(180);
        $message = new YiiMailMessage();

        $message->setContentType("text/html");
        $message->setTo(explode(',', $to));
        $message->setFrom(array(Yii::app()->params['systemEmail'] => 'join'));
        $message->setSubject($title);
        $message->setBody($content);

        $result['result'] = true;
        try {
            Yii::app()->mail->send($message);
        } catch (Swift_ConnectionException $e) {
            $result['result'] = false;
            $result['error'] = 'There was a problem communicating with SMTP: ' . $e->getMessage();
        }
        return $result;
    }

    /**
     * @param string $string 原文或者密文
     * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
     * @param string $key 密钥
     * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
     * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
     *
     * @example
     *
     *  $a = authcode('abc', 'ENCODE', 'key');
     *  $b = authcode($a, 'DECODE', 'key');  // $b(abc)
     *
     *  $a = authcode('abc', 'ENCODE', 'key', 3600);
     *  $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
     */
    public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {

        $ckey_length = 4;
        // 随机密钥长度 取值 0-32;
        // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
        // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
        // 当此值为 0 时，则不产生随机密钥

        $key = md5($key ? $key : 'jowinright'); //这里可以填写默认key值
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }

}

?>